package io.gitee.yxsnake.tenant.datasource.handler;

import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import io.gitee.yxsnake.tenant.datasource.configuration.properties.MybatisPlusExtProperties;
import io.gitee.yxsnake.tenant.datasource.context.TenantIgnoreContextHolder;
import io.gitee.yxsnake.embark.web.core.context.UserContext;
import lombok.AllArgsConstructor;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.StringValue;
import org.dromara.hutool.core.collection.CollUtil;

import java.util.List;

/**
 * @author: snake
 * @create-time: 2024-10-10
 * @description:
 * @version: 1.0
 */
@AllArgsConstructor
public class CustomTenantHandler implements TenantLineHandler {

    private final MybatisPlusExtProperties mybatisPlusExtProperties;

    @Override
    public Expression getTenantId() {
        // 假设有一个租户上下文，能够从中获取当前用户的租户
        String tenantId = UserContext.getTenantId();
        // 返回租户ID的表达式，StringValue 是 JSQLParser 中表示 string 类型的 class
        return new StringValue(tenantId);
    }

    @Override
    public String getTenantIdColumn() {
        return mybatisPlusExtProperties.getTenantColumn();
    }

    @Override
    public boolean ignoreTable(String tableName) {
        boolean b = TenantIgnoreContextHolder.get();
        if(b){
            TenantIgnoreContextHolder.remove();
            return true;
        }else{
            List<String> ignoreTables = mybatisPlusExtProperties.getIgnoreTables();
            if(CollUtil.isNotEmpty(ignoreTables)){
                return ignoreTables.contains(tableName);
            }
            // 根据需要返回是否忽略该表
            return false;
        }
    }
}
